//
//  CCLocation.m
//  Activity
//
//  Created by its on 15/5/29.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCLocation.h"
#import <CoreLocation/CoreLocation.h>

@interface CCLocation () <CLLocationManagerDelegate>
@property(nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, copy) void (^result)(NSDictionary *result, NSError *error);

@end

@implementation CCLocation

- (void)startLocaion:(void (^)(NSDictionary *result, NSError *error))result {
  self.locationManager = [[CLLocationManager alloc] init];
  self.locationManager.delegate = self;
  self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
  self.locationManager.distanceFilter = 10.0f;
  [self.locationManager requestWhenInUseAuthorization];
  [self.locationManager startUpdatingLocation];
  
  self.result = [result copy];
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
  [self.locationManager stopUpdatingLocation];
  CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
  [geoCoder reverseGeocodeLocation:newLocation
                 completionHandler:^(NSArray *placemarks, NSError *error) {
                   if (!error) {
                     NSString *test;
                     for (CLPlacemark *placemark in placemarks) {
                       test = [placemark locality];
                       if (!test) {
                         test = placemark.administrativeArea;
                       }
                     }
                     _result(@{@"city":test}, error);
                   } else {
                     _result(nil, error);
                   }
                 }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
  if (error.code == kCLErrorDenied)  {
    self.result(nil, error);
  } else if (error.code == kCLErrorNetwork)  {
    self.result(nil, error);
  }
}

- (void) dealloc {
  
}
@end
